define [
	'jquery'
	'helper'
	'template'
	'lib/jquery.couch.js'
], ($, H) ->
	S = {}
	$.fn.mb_donation_history = (SamCtx) ->

		# --- Global Variables and Function ---------------

		$select = 
			"non-member":
				amount : ""
				type2 : ".all"
				text : "$14 and less"
			"low-income":
				amount : "$15.00"
				type2 : ".all"
				text : "$15 - $24"
			"personal":
				amount : "$25.00"
				type2 : ".all"
				text : "$25 - $39"
			"family":
				amount : "$45.00"
				type2 : ".family"
				text : "$40 and up"
		donorID = ''
		$this = $(ins = @)
		S = SamCtx
		$tpl = $('<tr>').html '''
			<td><%= num+1 %></td>
			<td><%= donation_date%></td>
			<td>$<%= donation_amount %></td>
		'''
		$selTPL = $('<div>').html '<input name="<%=  %>" />'

		# --- Core code of plugin -------------------------

		unless @mb_plugin()
			@mb_plugin 'donation_history'

			# Initialization, adds table
			$this.find('.content').append '''
				<table class='records'>
					<tbody>
						<tr>
							<th> Record </th>
							<th> Date </th>
							<th> Amount </th>
						</tr>
					</tbody>
				</table>
			'''

			$('.ind.add').append $('<option>').val(i).html(o.text) for i, o of $select

			$.subscribe 'mb.query', (e, arg) ->
				t = arg['search_type']
				$(".add.#{t}", $this).show()
				$(".add:not(.#{t})", $this).hide()

			# Main subscription to obtain a donor_id
			$.subscribe 'mb.donor', (e, arg) ->
				donorID = arg['donor_id']

				# Remove all non-header table rows (cleans the table)
				$('.content tr:not(:has(th))', $this).remove()

				# Query for all donation records using the donor_id
				H.db().view 'app/donations', {key: donorID, success: (data) ->

					# Create an empty array, then copy all of value object into this array
					# This is done so sorting can be accomplished
					recordlist = []
					recordlist[i] = o.value for i, o of data.rows

					# Sort the array by donation date starting from most recent
					# Loop through this array and display the table of donations
					for i, x of recordlist.sort H.sortby 'donation_date', true
						content = S.content $tpl,
							num: Number(i)
							donation_date: x.donation_date
							donation_amount: x.donation_amount
						$('.content tbody', $this).append $('<tr>')
							.attr('id', x._id)
							.attr('index', Number(i)+1)
							.append content

					# This is kind of messy, I can't seem to get the width of a hidden table so I have
					# to clone it and hide it somewhere out of sight in order to calculate the dimensions and then
					# delete it afterwards.
					$('body').append $('table.records', $this).clone().attr('id', 'hidden').show()
						.css("position" 	: "absolute",
							"top"		: "-1000px" )
					$('.content', $this).css('width', "#{$('#hidden').width()+40}px")
					$('#hidden').remove()
					}

				return # return for the subscription


			# --- Button Event Handlers ------------------

			$('[name="add_donation"]', $this).on 'click', ->
				if $('select.add', $this).is(':hidden')
					type = '.org'
					amount = type2 = ''
				else
					type = '.ind'
					amount = $select[$('select.add', ins).val()].amount
					type2 = $select[$('select.add', ins).val()].type2

				$.publish 'mb.add_donation',
					donor_id: donorID
					amount: amount
					class1: type
					class2: type2
				S.app.setLocation '#/add_donation'
				return false

			# When a table row is clicked on, change background color to gray 
			# to mimic the "select" of options in an HTML selector, also modify the
			# selected row to have a classname of "selected"
			$('.content table', $this).on 'mousedown', 'tr:not(:has(th))', ->
				$.publish 'mb.donation', id: $(@).attr('id')
				S.app.setLocation '#/donation_detail'
				return

		return @
	return
